const request = indexedDB.open('notes', 1); //创建 Indexed DB 数据库

request.onupgradeneeded = function(event) { //创建对象存储区
	const db = event.target.result;
	const objectStore = db.createObjectStore('notes', {
		keyPath: 'id',
		autoIncrement: true
	});
	objectStore.createIndex('title', 'title', {
		unique: false
	});
	objectStore.createIndex('content', 'content', {
		unique: false
	});
};

request.onerror = function(event) { //数据库访问错误的回调函数
	console.log('打开数据库时发生错误');
};

request.onsuccess = function(event) { //数据库访问成功的回调函数
	const db = event.target.result;
	const form = document.querySelector('form');
	const title = document.getElementById('title');
	const content = document.getElementById('content');
	const noteList = document.getElementById('note-list');

	displayNotes();

	form.addEventListener('submit', function(event) { //监听表单数据
		event.preventDefault();
		const note = {
			title: title.value,
			content: content.value
		};
		const transaction = db.transaction(['notes'], 'readwrite');
		const objectStore = transaction.objectStore('notes');
		const request = objectStore.add(note);

		request.onsuccess = function() {
			displayNotes();
			title.value = '';
			content.value = '';
		};

		transaction.oncomplete = function() {
			console.log('笔记已添加');
		};

		transaction.onerror = function(event) {
			console.log('添加笔记时发生错误');
		};
	});

	function displayNotes() { //添加并且展示笔记
		while (noteList.firstChild) {
			noteList.removeChild(noteList.firstChild);
		}

		const objectStore = db.transaction('notes').objectStore('notes');

		objectStore.openCursor().onsuccess = function(event) {
			const cursor = event.target.result;
			if (cursor) {
				const note = document.createElement('li');
				const deleteButton = document.createElement('button');
				note.textContent = `${cursor.value.title}: ${cursor.value.content}`;
				deleteButton.textContent = '删除';
				note.appendChild(deleteButton);
				noteList.appendChild(note);
				deleteButton.onclick = function() {
					deleteNote(cursor.value.id);
					noteList.removeChild(note);
				};
				cursor.continue();
			} else {
				console.log('没有更多笔记');
			}
		};
	}

	function deleteNote(id) { //删除笔记
		const transaction = db.transaction(['notes'], 'readwrite');
		const objectStore = transaction.objectStore('notes');
		const request = objectStore.delete(id);

		transaction.oncomplete = function() {
			console.log('笔记已删除');
		};

		request.onerror = function(event) {
			console.log('删除笔记时发生错误');
		};
	}
}